//新增用户
import React, { useState, useEffect } from 'react'
import { Button, Card, DatePicker, Divider, Form, Input, InputNumber, notification, Select, TreeSelect } from 'antd'
import { FrownOutlined,createFromIconfontCN } from '@ant-design/icons'
import useStore from '../../components/useStore'
import dayjs from 'dayjs';
import request from '../../untils/request.js'

const IconFont = createFromIconfontCN({
  scriptUrl: require('../../../devDocument/icon.js'), // 根据实际路径调整
});

const InsertUser = () => {//新增一个用户

    const [form] = Form.useForm();
    const { collapsed,setnowroute } = useStore();
    const [roleOptions,setroleOptions]=useState([])//用户可选角色
    const [frameworkOptions,setframeworkOptions]=useState([])//可选的组织架构

    useEffect(()=>{
        form.setFieldsValue({//设置默认选择默认用户
            role_id:2,
            framework_id:null,//组织架构默认为空
            phone:null,//电话号码默认为空
            position:null,//职务默认为空
            birthday:null,//生日默认为空
            board_date:null,//入职日期默认为空
        })
        request("/admin/role/getRoleList", {//获取角色的可选列表（处超级管理员以外均可分配）
            mode: 'cors'
        }).then(data => {
            for(var i=0;i<data.length;i++){
                data[i]={
                    value:data[i].id,
                    label:data[i].role_name
                }
            }
            setroleOptions(data)
        })
        request("/admin/framework/getFramework", {//获取组织架构的可选列表
            mode: 'cors'
        }).then(data => {
            data[0].disabled=true//根节点禁止挂载用户
            setframeworkOptions(data)
        })
    },[])

    const toExcel=async ()=>{
        setnowroute({...{route:"/ship/sys/insertUserByExcel",title:"excel导入用户"}})
    }

    const getPassword=()=>{//生成随机密码
        const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        const passwordLength = Math.floor(Math.random() * 15) + 6; // 6-20位
        let password = "";
        // 生成随机密码
        for (let i = 0; i < passwordLength; i++) {
            const randomIndex = Math.floor(Math.random() * charset.length);
            password += charset[randomIndex];
        }
        form.setFieldValue("password",password)
    }

    const insertUser= async ()=>{
        try {//通过验证
            var req = await form.validateFields();
            req={
                ...req,
                birthday: req.birthday ? dayjs(req.birthday).format("YYYY-MM-DD") : null,
                board_date: req.board_date ? dayjs(req.board_date).format("YYYY-MM-DD") : null
            }
            request("/admin/user/insertUser", {//新增用户
                method:"POST",
                mode: 'cors',
                body:req
            }).then(data => {
                if (data.code == 200) {
                    notification.success({
                        message:data.msg
                    })
                } else {
                    notification.error({
                        message:data.msg,
                        icon:<FrownOutlined />
                    })
                }
            })
        } catch (errorInfo) {
            notification.open({
                message:"请检查填写信息是否有误",
                icon:<FrownOutlined />
            })
        }
    }

    return (
        <div style={{ height: "94%", backgroundColor: `#F1F1F1`,right:"1%",top:"4vh",overflow:"hidden",
        backgroundSize: "100% 100%", width: collapsed?"94%":"84%", position: "absolute",  color: "white", fontSize: "0.8rem"}}>
            <div style={styles.kshcontainer}>
                <div style={{
                    fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", backgroundColor: "", display: "flex",
                    textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
                }}>
                    <Button type="primary" onClick={toExcel} style={{marginTop:"2vh"}}>
                        <IconFont type="icon-Excel" />通过excel表格导入
                    </Button>
                    <Card style={{width:"100%",marginTop:"2vh"}}>
                        <div style={{ 
                            maxHeight: '75vh',  // 限制最大高度（可根据需求调整）
                            overflowY: 'auto',  // 纵向溢出时显示滚动条
                            overflowX: 'hidden', // 横向溢出时隐藏
                            paddingRight: '8px' // 避免滚动条遮挡内容（可选）
                        }}>
                            <Form
                                form={form}
                                labelCol={{ span: 6 }}
                                wrapperCol={{ span: 18 }}
                                style={{ maxWidth: 800 }}
                            >
                            <Form.Item
                                label="用户姓名"
                                name="name"
                                rules={[{ required: true, message: '用户姓名不能为空' }]}
                            >
                                <Input maxLength={20} showCount placeholder='请输入用户姓名' />
                            </Form.Item>

                            <Form.Item
                                label="用户角色"
                                name="role_id"
                                rules={[{ required: true, message: '请选择用户角色' }]}
                            >
                                <Select options={roleOptions} placeholder="请选择用户角色" />
                            </Form.Item>

                            <Form.Item
                                label="手机号码"
                                name="phone"
                                rules={[
                                () => ({
                                    validator(_, value) {
                                    if (!value) return Promise.resolve();
                                    const phoneRegex = /^1[3-9]\d{9}$/;
                                    if (phoneRegex.test(value)) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('请输入正确的手机号码'));
                                    }
                                })
                                ]}
                            >
                                <Input maxLength={11} showCount placeholder='请输入手机号码（非必填）' />
                            </Form.Item>

                            <Form.Item
                                label="工号"
                                name="work_number"
                                rules={[
                                { required: true, message: '工号不能为空' },
                                () => ({
                                    validator(_, value) {
                                    if (value === undefined || value === null) return Promise.resolve();
                                    if (Number.isInteger(value) && value > 0) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('请输入大于0的整数'));
                                    },
                                }),
                                ]}
                            >
                                <InputNumber
                                min={1}
                                autoComplete="new-password"
                                precision={0}
                                maxLength={10}
                                controls={false}
                                style={{ width: '100%' }}
                                placeholder="请输入正整数（工号即为登入账号）"
                                onPaste={(e) => {
                                    const paste = e.clipboardData.getData('text');
                                    if (!/^\d+$/.test(paste)) {
                                    e.preventDefault();
                                    }
                                }}
                                formatter={(value) => `${value}`.replace(/\D/g, '')}
                                parser={(value) => value?.replace(/\D/g, '')}
                                />
                            </Form.Item>

                            <Form.Item
                                label="密码"
                                name="password"
                                rules={[
                                { required: true, message: '请输入密码' },
                                () => ({
                                    validator(_, value) {
                                    if (!value || (value.length >= 6 && value.length <= 20)) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('密码长度必须为6-20位'));
                                    },
                                })
                                ]}
                            >
                                <Input.Password
                                autoComplete="new-password"
                                maxLength={20}
                                showCount
                                placeholder='请输入登入密码'
                                />
                            </Form.Item>

                            <Form.Item wrapperCol={{ offset: 6, span: 18 }}>
                                <Button onClick={getPassword}>生成随机密码</Button>
                            </Form.Item>

                            <Form.Item
                                label="所属架构"
                                name="framework_id"
                                rules={[{ required: false }]}
                            >
                                <TreeSelect
                                treeData={frameworkOptions}
                                treeDefaultExpandedKeys={['1']}
                                allowClear
                                placeholder="请选择所属架构"
                                />
                            </Form.Item>

                            <Form.Item
                                label="职务"
                                name="position"
                                rules={[{ required: false }]}
                            >
                                <Input maxLength={50} showCount placeholder='请输入职务' />
                            </Form.Item>

                            <Form.Item
                                label="出生日期"
                                name="birthday"
                                rules={[{ required: false }]}
                            >
                                <DatePicker placeholder='请选择出生日期' />
                            </Form.Item>

                            <Form.Item
                                label="入职日期"
                                name="board_date"
                                rules={[{ required: false }]}
                            >
                                <DatePicker placeholder='请选择入职日期' />
                            </Form.Item>

                            <Divider />

                            <Form.Item wrapperCol={{ offset: 6, span: 18 }}>
                                <span style={{ color: '#666' }}>新注册的用户，账号与用户状态均为正常，如需更改请前往用户界面更改。</span>
                            </Form.Item>

                            <Form.Item wrapperCol={{ offset: 6, span: 18 }}>
                                <Button type="primary" onClick={insertUser}>注册</Button>
                            </Form.Item>
                            </Form>
                        </div>
                    </Card>
                </div>
            </div>
        </div>
    )
}

export default InsertUser

var styles = {
    maincontainer: {
        height: "100vh", 
        backgroundColor: `white`,
        backgroundSize: "100% 100%", 
        width: "100%", 
        position: "absolute", left: "0", 
        color: "white", 
        fontSize: "0.8rem"
    },
    topcontainer: {
        width: "100%", 
        height: "10vw", 
        backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", 
        paddingTop: "3vw",
        position: "relative", 
        fontSize: "0.89rem", 
        textIndent: "2rem", 
        fontWeight: "800", 
        color: "#a91f24", 
        borderRadius: "0 0 15px 15px"
    },
    butdcstyle: { paddingLeft:"1vw",
        paddingRight:"1vw",height: "2vw", 
        position: "absolute", 
        right: "1%", top: "0%", 
        backgroundColor: "#a91f24", 
        fontSize: "0.8vw", 
        borderRadius: "0.4rem", 
        borderRadius: "0 0 0.3vw 0.3vw" },
    butmainstyle: {
        paddingLeft:"1vw", 
        height: "2vw", 
        position: "absolute", 
        right: "6.5%", top: "0%", 
        backgroundColor: "#a91f24", 
        fontSize: "0.8vw", 
        borderRadius: "0.4rem", 
        borderRadius: "0 0 0.3vw 0.3vw" },
    butbackstyle: { 
        borderRadius: "0.4rem", 
        backgroundColor: "#a91f24", 
        height: "2vw", 
        position: "absolute", 
        right: "12%", top: "0%",
        fontSize: "0.8vw", 
        borderRadius: "0 0 0.3vw 0.3vw"},
    kshcontainer: {
        width: "98%", 
        height: "95%", 
        position: "absolute", top: "3%", 
        left: "1%", backgroundColor: "white", 
        color: "black",
        borderRadius: "10px",
    },
}